package pl.darbat.photogallery;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import pl.darbat.photogallery.Debug.MemoryStatusListener;
import pl.darbat.photogallery.html.HtmlDownloader;
import pl.darbat.photogallery.html.HtmlDownloaderListener;
import pl.darbat.photogallery.html.HtmlParser;
import pl.darbat.photogallery.html.HtmlParserListener;
import pl.darbat.photogallery.list.PhotoListAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class CategoryGridActivity extends Activity implements OnItemClickListener, HtmlParserListener, HtmlDownloaderListener, OnCancelListener, MemoryStatusListener {

	private static final String TAG = "CategoryGridActivity";
	
	private GridView mGridView;
	private PhotoListAdapter mGridAdapter;
	
	private String[] mFrom = new String[] { "miniImage", "description"};
	private int[] mInsertTo = new int[] { R.id.gridElementImage, R.id.gridElementDescription};
	
	private List<Map<String, String>> mGridList;
	private String mCategoryLink;
	private ProgressDialog mProgressDialog;
	
	private long mStartTime;
	private boolean isCanceled = false;
	HtmlParser mHtmlParser = null;
	HtmlDownloader mHtmlDownloader = null;
	
	private Thread mMemoryStatus;

	private TextView mTitleView;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onCreate");
		setContentView(R.layout.grid);
		mGridView = (GridView) findViewById(R.id.gridMosaic);
		
		Intent intent = getIntent();
		if(intent != null){
			mCategoryLink = intent.getExtras().getString("categoryLink");
		}
		if(mCategoryLink == null){
			if(Debug.CATEGORYGRIDACTIVITY) Log.w(TAG, "No category link found, opening default category");
			String[] defaultLinks = getResources().getStringArray(R.array.categoryLink);
			mCategoryLink = defaultLinks[0];
		}
		
		mProgressDialog = ProgressDialog.show(this,getResources().getString(R.string.data_downloading),getResources().getString(R.string.please_wait),true,true);
		mProgressDialog.setOnCancelListener(this);

		mStartTime = System.currentTimeMillis();

		try {
			URL categoryUrl = new URL(mCategoryLink);

			if(categoryUrl != null){
				if(mHtmlDownloader == null){
					mHtmlDownloader = new HtmlDownloader();
					mHtmlDownloader.setHtmlDownloaderListener(this);
				}
				mHtmlDownloader.asyncDownloadPage(categoryUrl);
			}
		} catch (MalformedURLException e) {
			Log.e(TAG,"",e);
			error();
		}
	
		mTitleView = (TextView) findViewById(R.id.gridTitleBar);
		mMemoryStatus = Debug.createMemoryStatusThread(this);
		mMemoryStatus.start();
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onPause");
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onRestart");
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onDestroy");
		cleanUp();
	}
	
	protected void cleanUp(){
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"cleanUp");
		if(mGridAdapter != null){
			mGridAdapter.cleanUp();
			mGridAdapter = null;
		}
		if(mGridList != null){
			mGridList.clear();
			mGridList = null;
		}
		mHtmlParser = null;
		mHtmlDownloader = null;
		mGridView = null;
		System.gc();
	}



	private void error(){
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"error");
		//Toast.makeText(this, getResources().getString(R.string.data_error), Toast.LENGTH_LONG);
		mProgressDialog.dismiss();
		finish();
	}
	

	public void onItemClick(AdapterView parent, View v, int position, long id) {
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onItemClick");

		Intent intent = new Intent(this, PhotoActivity.class);
		
		ArrayList<String> miniImageLinks = new ArrayList<String>();
		ArrayList<String> fullImageLinks = new ArrayList<String>();
		ArrayList<String> pageLinks = new ArrayList<String>();
		ArrayList<String> descriptions = new ArrayList<String>();
		for(int i=0; i<mGridList.size(); i++){
			miniImageLinks.add(mGridList.get(i).get("miniImage"));
			fullImageLinks.add(mGridList.get(i).get("fullImage"));
			pageLinks.add(mGridList.get(i).get("link"));
			descriptions.add(mGridList.get(i).get("description"));
		}
		intent.putExtra("miniImageLinks", fullImageLinks);
		intent.putExtra("fullImageLinks", fullImageLinks);
		intent.putExtra("pageLinks", pageLinks);
		intent.putExtra("descriptions", descriptions);
		
		intent.putExtra("position", position);

		//Open Browser:
		//String url = (String) mGridList.get(position).get("link");
		//Intent intent = new Intent(Intent.ACTION_VIEW);
		//intent.setData(Uri.parse(url));
		startActivity(intent);
	}
	
	
	public void onDownloadResult(InputStream is) {
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onDownloadResult");
		if(!isCanceled){
			if(is != null){
				if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"download time: " + (System.currentTimeMillis() - mStartTime));
				if(mHtmlParser == null){
					mHtmlParser = new HtmlParser();
					mHtmlParser.setHtmlParserListener(this);
				}
				runOnUiThread(new Runnable(){
						public void run() {
							mProgressDialog.setTitle(getResources().getString(R.string.data_parsing));
						}
				});
				mHtmlParser.asyncParsePage(is);
			} else {
				if(Debug.CATEGORYGRIDACTIVITY) Log.w(TAG, "onDownloadResult: no result returned");
				error();
			}
		}
	}

	public void onParseResult(List<Map<String, String>> list) {
		if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onParseResult");

		if(!isCanceled){
			mGridList = list;
			if(mGridList != null){
				if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"download and parse time: " + (System.currentTimeMillis() - mStartTime));
				
				if(mGridAdapter == null) {
					mGridAdapter = new PhotoListAdapter(getApplicationContext(), mGridList, R.layout.grid_row, mFrom, mInsertTo, R.drawable.pl_foto_com, 50);
				} else {
					mGridAdapter.notifyDataSetChanged();
				}
				runOnUiThread(new Runnable(){
					public void run() {
						mGridView.setOnItemClickListener(CategoryGridActivity.this);
						mGridView.setAdapter(mGridAdapter);
						mGridView.setOnScrollListener(mGridAdapter); //slow adapter
					}
				});
				mProgressDialog.dismiss();
			} else {
				if(Debug.CATEGORYGRIDACTIVITY) Log.w(TAG, "onParseResult: no result returned");
				error();
			}
		}
	}

	public void onCancel(DialogInterface di) {
		isCanceled = true;
		if(mHtmlParser != null){
			mHtmlParser.cancel();
		}
		finish();
	}
	
	public void onMemoryStatus(final String status) {
		runOnUiThread(new Runnable(){
			public void run() {
				mTitleView.setText(status);
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(Debug.CATEGORYGRIDACTIVITY) Log.v(TAG,"onKeyBack");
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}



}
